package top.eggcode.setup.config.shiro;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import top.eggcode.common.consts.ResponseStatus;
import top.eggcode.common.mvc.HttpResponseUtil;
import top.eggcode.common.mvc.Responser;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * Title: 检查会话
 * Description: 用户必须携带登录标识
 * Date: 2021/4/17 20:05
 *
 * @author JiaQi Ding
 * @version 1.0
 */
public class SessionFilter extends AccessControlFilter {

    private final static long GLOBAL_SESSION_TIMEOUT = 1800L;

    /**
     * 是否允许访问
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {

        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

        // 会话标识
        String sessionId = httpRequest.getHeader("Session-Id");

        if (StringUtils.isEmpty(sessionId)) {

            // 未携带Token
            HttpResponseUtil.sendJson(
                    (HttpServletResponse) servletResponse,
                    Responser.failure(ResponseStatus.REQ_NO_TOKEN)
            );
            // 拒绝访问
            return false;
        }

        Subject subject = getSubject(servletRequest, servletResponse);
        Session session = subject.getSession();
        //Session session = SessionHelper.getSessionManager().getSession(sessionId);

        List<Object> keys = Arrays.asList(session.getAttributeKeys().toArray());
        if (!subject.isAuthenticated()) {
            HttpResponseUtil.sendJson((HttpServletResponse) servletResponse,
                    Responser.failure(ResponseStatus.USER_UNAUTHENTICATED));
            return false;
        }

        return true;
    }

    /**
     * 访问拒绝后的处理（isAccessAllowed 返回 false）
     * true 让过滤链继续执行，false 请求结束
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {

        // 请求结束
        return false;
    }
}
